package com.example.master.controller;


import com.example.master.dto.*;
import com.example.master.entity.vo.*;
import com.example.master.service.*;
import com.example.master.utils.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.web.bind.annotation.*;
import sun.misc.*;

import javax.imageio.*;
import java.awt.image.*;
import java.io.*;

/**
 * @Author zcb
 * @PackageName a-great-masters
 * @Package com.example.master.controller
 * @Date 2023/2/6 14:31
 * @Version 1.0
 */
@RestController
@RequestMapping("/order")
@Api(tags = "订单模块", value = "用户Open api 入口")
public class OrderController {

    @Autowired
     private OrderUtils orderUtils;

    @Autowired
    OrderService orderService;

    @ApiOperation(value = "购买")
    @GetMapping("/{serviceId}")
    public Result<PurchaseVO> purchase(@PathVariable Integer serviceId){

        return orderService.getServiceInfo(serviceId);
    }


    @ApiOperation(value = "生成和存放订单表")
    @PostMapping("/orderNo")
    public Result orderNumber(@RequestBody OrderNoVO orderNoVO) {

        return orderService.getOrderInfo(orderNoVO.getServiceId(),orderNoVO.getUserId(),orderNoVO.getRemark());
    }



    @ApiOperation(value = "生成二维码")
    @GetMapping("/qr/{orderNo}")
    public Result qR(@PathVariable("orderNo") String orderNo){
        //根据订单号获取service_id
        if (orderNo == null){
            return Result.error("订单号不能为空");
        }
        OrderDTO orderDTO = orderService.getServiceByOrderNo(orderNo);
        Long price = orderDTO.getPrice();
        String m = price.toString();
        String baseUrl= "https://biz.earku.com/ShareShop/z_pay_wap.html?shopId=";
        Integer shopId = 10264;
        String thirdOrderNo = orderUtils.getOrderCode(orderDTO.getUserId());
        String thirdReturnUrl = "http://localhost:9000/paySuccess";
        String thirdNotifyUrl = "ok";

        String payUrl = baseUrl + shopId + "&m=" + m + "&thirdOrderNo=" + thirdOrderNo
                + "&thirdReturnUrl=" + thirdReturnUrl + "&thirdNotifyUrl="+thirdNotifyUrl;

        BufferedImage image = QRCodeUtil.createImage("utf-8", payUrl, 30, 30);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());
        return Result.success(base64Img);
    }















}
